package com.example.contentproviderdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;

import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;

import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.tbruyelle.rxpermissions3.RxPermissions;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import io.reactivex.rxjava3.functions.Consumer;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "tag";
    private ContentResolver resolver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
            RxPermissions rx = new RxPermissions(this);
            //if(!rx.isGranted(Manifest.permission.READ_CONTACTS)) {
                rx.request(Manifest.permission.READ_CONTACTS,
                        Manifest.permission.WRITE_CONTACTS,
                        Manifest.permission.READ_SMS).
                        subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Throwable {
                        if (aBoolean) {
                           //intiSMS();
                            //intiData();
                            //intiQuery();
                            //intiView();
                            intiAdd();

                        }
                    }
                });

            //}else{
                //intiSMS();
                //intiData();
                //intiQuery();

          //  }
    }
    private void intiView(){
        EditText editText=findViewById(R.id.edit_contact);
        Button button=findViewById(R.id.but_query);
        TextView textView=findViewById(R.id.text_contact);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number=editText.getText().toString();
                textView.setText(intiQuery(number));
            }
        });
    }

    private void intiSMS(){
        resolver=getContentResolver();
        Cursor cursor=resolver.query(Telephony.Sms.CONTENT_URI,
                new String[]{Telephony.Sms.ADDRESS, Telephony.Sms.DATE, Telephony.Sms.TYPE, Telephony.Sms.BODY},
                null,null,null);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cursor.moveToFirst();
        do {
            String address=cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));
            String date=cursor.getString(cursor.getColumnIndex(Telephony.Sms.DATE));
            String type=cursor.getString(cursor.getColumnIndex(Telephony.Sms.TYPE));
            String body=cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));

            Log.d(TAG,"发送者："+address+"时间"+simpleDateFormat.format(new Date(Long.parseLong(date)))+"类型"+type+"内容"+body);

        }while(cursor.moveToNext());
        cursor.close();


    }

    private void intiData(){
        resolver=getContentResolver();
        Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        Cursor cursor=resolver.query(uri,null,null,null,null);
        cursor.moveToFirst();
            do {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                Log.d(TAG, "姓名：" + name);
                Log.d(TAG, "电话：" + phone);

            } while (cursor.moveToNext());
            cursor.close();

    }

    private String intiQuery(String number){

        //String number="/1 345-789-7577";

        Uri uri=Uri.parse(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI+"/"+number);
        resolver=getContentResolver();
        Cursor cursor=resolver.query(uri,null,
                null,null,null);
        StringBuffer sb=new StringBuffer();
        if (cursor.moveToFirst()){
            String name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phone=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.d(TAG,number+"对应联系人的名称"+name);
            sb.append("联系人：").append(name).append("\t电话号码：").append(phone).append("\n");
        }
        cursor.close();
        return  sb.toString();
    }

    private void intiAdd() {
        ContentProviderOperation op1 = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).
                withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "VICT").
                withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.example.contentproviderdemo").
                withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
                        ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED).build();

        ContentProviderOperation op2 = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).
                withValueBackReference(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, 0).
                withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).
                withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "小刘").build();


        ContentProviderOperation op3 = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).
                withValueBackReference(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, 0).
                withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).
                withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).
                withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "18923456708").
                withValue(ContactsContract.Data.IS_PRIMARY, "1").build();

        ContentProviderOperation op4 = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).
                withValueBackReference(ContactsContract.CommonDataKinds.Email.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Email.DATA, "1567099080@163.com")
                .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_MOBILE).build();

        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        operations.add(op1);
        operations.add(op2);
        operations.add(op3);
        operations.add(op4);

        try {
            getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations);
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }
    }